package io.easyspring.invitation.core.impl;

import io.easyspring.invitation.core.InvitationEventPublisher;
import io.easyspring.invitation.core.InvitationProcessor;
import io.easyspring.invitation.core.InvitationRepository;
import io.easyspring.invitation.core.support.EasyInvitation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;

import java.util.List;

/**
 * 抽象的邀请信息处理器
 *
 * @author summer
 * @version 2.0.0-RELEASE
 * DateTime 2019-06-22 13:00
 */
@Slf4j
@Validated
public abstract class AbstractInvitationProcessor<T extends EasyInvitation> implements InvitationProcessor<T> {

    /**
     * 注入邀请信息的存储器
     */
    @Autowired
    private InvitationRepository invitationRepository;
    /**
     * 注入邀请信息的事件发送器
     */
    @Autowired
    private InvitationEventPublisher invitationEventPublisher;

    /**
     * 发送邀请的方法
     *
     * @param easyInvitation 邀请信息
     * @param expires 有效时长
     * @return T
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-06-22 13:21
     */
    @Override
    @SuppressWarnings("unchecked")
    public T send(T easyInvitation, Long expires) {
        // 保存邀请信息
        invitationRepository.save(easyInvitation, expires);

        // 发送邀请信息发送成功事件
        invitationEventPublisher.publishInvitationSendSuccessEvent(this, easyInvitation);

        return easyInvitation;
    }

    /**
     * 撤销邀请信息的方法
     *
     * @param inviterId 邀请者 id
     * @param verificationCode 邀请验证码
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-06-22 13:36
     */
    @Override
    public int recall(Long inviterId, String verificationCode) {
        // 删除邀请信息
        return invitationRepository.remove(inviterId, verificationCode);
    }

    /**
     * 获取单个邀请信息的方法
     *
     * @param inviterId 邀请者 id
     * @param verificationCode 验证码
     * @return T
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-06-22 17:33
     */
    @Override
    @SuppressWarnings("unchecked")
    public T get(Long inviterId, String verificationCode) {
        // 查询数据并返回
        return (T) invitationRepository.get(inviterId, verificationCode);
    }

    /**
     * 根据邀请者 id 获取其所有邀请信息的方法
     *
     * @param inviterId 邀请者 id
     * @return java.util.List<T>
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-06-22 13:39
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<T> list(Long inviterId) {
        // 执行查询并返回结果
        return invitationRepository.list(inviterId);
    }
}
